/**
 * 
 */
package com.md.controller;

import java.lang.reflect.ParameterizedType;
import java.util.Map;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.md.entity.BaseEntity;
import com.md.entity.TestLock;
import com.md.model.BaseModel;
import com.md.model.StandardFormModel;
import com.md.model.StandardListModel;
import com.md.util.DataUtils;

/**
 * @author yehao
 *
 */
public abstract class StandardFormController<T> extends BaseController{
	
	private Class<?> recordClass = null;
	
	public StandardFormController(){
		ParameterizedType parameterizedType = (ParameterizedType) this.getClass().getGenericSuperclass();
		recordClass = (Class<?>) parameterizedType.getActualTypeArguments()[0];
	}
	
	@Override
	public void setModel() {
		BaseModel baseModel = new StandardFormModel();
		if (modelMap == null) {
			modelMap = new ModelMap();
			modelMap.addAttribute("model", baseModel);
		}
	}
	
	@RequestMapping("/form")
	public ModelAndView form(@RequestParam Map<String,String> params) throws Exception{
		String recordId = params.get("recordId");
		Object record = null;
		if(!DataUtils.isBlank(recordId)){
			record = this.entityManager.find(recordClass, recordId);
		}else{
			record = recordClass.newInstance();
		}
		modelMap.addAttribute("record",  record);
		modelMap.addAttribute("recordJson", JSON.toJSON(record).toString());

		ModelAndView modelAndView = super.display();
		String[] views = modelAndView.getViewName().split("/");
		modelAndView.setViewName(views[0] + "/" + views[0] + "Form");
		return modelAndView;
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public Map<String,String> save(T record){
		
		BaseEntity baseEntity = (BaseEntity) record;
		if(DataUtils.isBlank(baseEntity.getIdentifier())){
			baseEntity.setIdentifier(null);
		}else{
			baseEntity = this.entityManager.merge(baseEntity);
		}
		
		this.beforeSave(record);
		
		this.entityManager.flush();
		
		this.entityManager.persist(baseEntity);
		
		this.entityManager.flush();
		
		this.afterSave(record);
		
		this.entityManager.flush();
		
		this.mes.put("recordId",baseEntity.getIdentifier().toString());
		
		return this.message("保存成功", true);
	}
	
	/**
	 * 保存前业务逻辑
	 * @author yehao
	 * @param record
	 */
	public abstract void beforeSave(T record);
	
	/**
	 * 保存后业务逻辑
	 * @author yehao
	 * @param record
	 */
	public abstract void afterSave(T record);
}
